package com.websocket.config.originWebsocket.handler;

import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @作者: 林江
 * @创建时间: 2023/12/18
 * @功能:
 */
public class MyWebSocketHandler extends AbstractWebSocketHandler {
    ConcurrentHashMap<String, WebSocketSession> concurrentHashMap = new ConcurrentHashMap();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("WS连接成功之后执行。。。。。。");
        concurrentHashMap.put(session.getId(), session);
    }

    /**
     * 处理文本消息
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println(message.getPayload());
        System.out.println("处理文本消息..................");
    }

    /**
     * 处理二进制消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        System.out.println("处理二进制消息......................");
    }

    /**
     * 处理ping消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        System.out.println("处理ping消息...................");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        concurrentHashMap.remove(session.getId());
        System.out.println("WS关闭的时候执行。。。。。。。。。。。。。。。。。");
    }

    /**
     * 服务端发送信息给客户端
     *
     * @param sessionId
     * @param obj
     */
    public void sendMsg(String sessionId, Object obj) throws IOException {
        TextMessage message = new TextMessage(obj.toString());
        for (WebSocketSession session : concurrentHashMap.values()) {
            session.sendMessage(message);
        }
    }
}
